package com.cmict.data.bpm.framework.bpm.core.event;

import com.cmict.data.bpm.dal.dataobject.definition.BpmProcessDefinitionExtDO;
import com.cmict.data.bpm.dal.dataobject.task.BpmProcessInstanceExtDO;
import com.cmict.data.bpm.dal.mysql.definition.BpmProcessDefinitionExtMapper;
import com.cmict.data.bpm.dal.mysql.task.BpmProcessInstanceExtMapper;
import com.cmict.data.bpm.enums.definition.BpmModelFormTypeEnum;
import com.cmict.data.form.api.task.FormDataApi;
import com.cmict.data.form.api.task.dto.SysFormDTO;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class BpmAllProcessInstanceResultEventListener implements ApplicationListener<BpmAllProcessInstanceResultEvent> {

    @Resource
    private BpmProcessInstanceExtMapper processInstanceExtMapper;

    @Resource
    private BpmProcessDefinitionExtMapper processDefinitionExtMapper;

    @Resource
    private FormDataApi formDataApi;

    @Override
    public void onApplicationEvent(BpmAllProcessInstanceResultEvent event) {
        //onEvent(event);
        BpmProcessInstanceExtDO processInstanceExt = processInstanceExtMapper.selectByProcessInstanceId(event.getId());
        String processDefinitionId = processInstanceExt.getProcessDefinitionId();
        Integer formRecordId = processInstanceExt.getFormRecordId();
        /**
         *  1.先查表单表获取当前流程对应的表名
         *  2.根据表名和formRecordId查询所对应的数据
         *  3.将该条数据的审批状态进行更新
         */
        BpmProcessDefinitionExtDO processDefinitionExt = processDefinitionExtMapper.selectByProcessDefinitionId(processDefinitionId);
        Long formId = processDefinitionExt.getFormId();
        if(BpmModelFormTypeEnum.CUSTOM.getType() == processDefinitionExt.getFormType()){
            SysFormDTO sysForm = formDataApi.getSysFormById(formId);
            String tableName = sysForm.getTableName();
            formDataApi.updata(tableName,formRecordId,event.getResult());
        }
    }
}
